import { ref } from 'vue'
import api from '../services/api'
import { useRouter } from 'vue-router'
import type { SuccessResponse, ErrorResponse, LoginResponse, TokenResponse } from '../types'  // 更新类型

export function useAuth() {
  const token = ref(localStorage.getItem('token'))
  const refreshToken = ref(localStorage.getItem('refreshToken'))
  const error = ref('')
  const router = useRouter()
  const isAuthenticated = ref(false)

  const login = async (username: string, password: string) => {
    try {
      const params = new URLSearchParams()
      params.append('username', username)
      params.append('password', password)
      const response = await api.post<SuccessResponse<LoginResponse>>('/v1/auth/login', params, {  // 指定版本
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      })
      isAuthenticated.value = true
      token.value = response.data.data.access_token
      refreshToken.value = response.data.data.refresh_token
      localStorage.setItem('token', response.data.data.access_token)
      localStorage.setItem('refreshToken', response.data.data.refresh_token)
      router.push('/numbers')
      return { success: true, data: response.data.data }
    } catch (error: any) {
      isAuthenticated.value = false
      throw new Error(error.response?.data?.message || '登录失败')
    }
  }

  const refreshAccessToken = async () => {
    try {
      if (!refreshToken.value) return false
      const { data } = await api.post<SuccessResponse<TokenResponse>>('/v1/auth/refresh-token', {  // 指定版本
        refresh_token: refreshToken.value
      })
      token.value = data.data.access_token
      localStorage.setItem('token', data.data.access_token)
      return true
    } catch (e) {
      logout()
      return false
    }
  }

  const logout = async () => {
    try {
      await api.post<SuccessResponse>('/v1/auth/logout')  // 指定版本
      localStorage.removeItem('token')
      localStorage.removeItem('refreshToken')
      token.value = null
      refreshToken.value = null
      isAuthenticated.value = false
      router.push('/login')
    } catch (e: any) {
      throw new Error(e.response?.data?.message || '退出失败')
    }
  }

  const register = async (username: string, password: string) => {
    try {
      await api.post<SuccessResponse>('/v1/auth/register', { username, password })  // 指定版本
      await login(username, password)
    } catch (e: any) {
      error.value = e.message
      throw new Error(error.value)
    }
  }

  return {
    token,
    refreshToken,
    error,
    login,
    logout,
    refreshAccessToken,
    register,
    isAuthenticated
  }
} 